<template>
  <NavBar title="登录"></NavBar>
  <van-form @submit="onSubmit" style="margin-top: 40px">
    <van-cell-group inset>
      <van-field
        v-model="state.username"
        name="username"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="state.password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="danger" native-type="submit">
        提交
      </van-button>
    </div>
    <div style="margin: 16px">
      <van-button round block type="success" @click="toRegister">
        去注册
      </van-button>
    </div>
  </van-form>
</template>

<script setup lang="ts">
import NavBar from "@/components/Navbar.vue";
import { reactive } from "vue";
import { useRouter } from "vue-router";
import { loginApi } from "@/api/user";
import { showToast } from "vant";

// const username = ref("");
// const password = ref("");
const state = reactive({
  username: "",
  password: "",
});

const onSubmit = async (values: any) => {
  console.log("submit", values);
  const res = await loginApi({
    loginname: state.username,
    password: state.password,
  });
  if (res) {
    localStorage.setItem("token", res.data.token);
    localStorage.setItem("userid", res.data.userid);
    showToast("登录成功");
    router.push("/home");
  }
};

// 跳转到注册页
const router = useRouter();
const toRegister = () => {
  router.push("/register");
};
</script>
